﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ResourceBasedAuthApp.Data;
using ResourceBasedAuthApp.Services;
using System.Reflection.Metadata;

namespace ResourceBasedAuthApp.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DocumentController : ControllerBase
    {
        private readonly IAuthorizationService _authorizationService;
        public DocumentController(IAuthorizationService service)
        {
            _authorizationService = service;
        }
        [HttpGet("GetAll")]
        public IActionResult GetAll()
        {
            return Ok(DocumentRepository.All());
        }

        [Authorize(Policy = "CustomRolePolicy")]
        [Authorize(Roles = "CustomRole")]
        [HttpGet("FindById")]
        public async  Task< IActionResult> FindById([FromQuery]int id)
        {
     
            var doc = DocumentRepository.FindById(id);
            if( ( await _authorizationService.AuthorizeAsync(User,doc, Operations.Read)).Succeeded)
            {
                return Ok(doc);
            }
            else
            {
                return new ForbidResult();
            }
           
        }
        [Authorize(Policy = "EditPolicy")]
        [HttpPost("Update")]
        public async  Task<IActionResult> Update([FromBody] DocumentEntity entity)
        {
            DocumentEntity document = DocumentRepository.FindById(entity.Id);

            if (document == null)
            {
                return new NotFoundResult();
            }
            //if ((await _authorizationService
            //    .AuthorizeAsync(User, document, "EditPolicy")).Succeeded)
            //{
               
            //}
            //if ((await _authorizationService
            //  .AuthorizeAsync(User,)).Succeeded)
            //{

            //}
            //else
            //{
            //    return new ChallengeResult();
            //}
            return Ok(DocumentRepository.Update(entity));
        }

        [HttpGet("Delete")]
        public IActionResult Delete([FromQuery] int  id)
        {
            return Ok(DocumentRepository.DeleteById(id));
        }
    }
}
